const db = uniCloud.database();
const _ = db.command;
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
 const now = new Date();
 
 // 1. 使用上海时间构建当前 Date 对象（关键改进）
 const shanghaiTimeStr = now.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
 console.log('上海时间：', shanghaiTimeStr);
 
 // 将时间字符串重新解析为 Date 对象（保持时区一致）
 const [dateStr, timeStr] = shanghaiTimeStr.split(' ');
 const [year, month, day] = dateStr.split(/[-/]/).map(Number);
 const [hour, minute, second] = timeStr.split(':').map(Number);
 
 // 构造真正的上海时区时间对象
 const shanghaiNow = new Date(year, month - 1, day, hour, minute, second || 0);
 const nowTimestamp = shanghaiNow.getTime();
 
 console.log('上海时间戳：', nowTimestamp);
 
 const uniIDIns = uniID.createInstance({ context });
 
 // 当前日期（用于匹配日期字段）
 const currentDateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
 
 const appoints = await db.collection('appoint_schedule').get();
 
 console.log('预约数据：', appoints);
 
 const recordsToProcess = appoints.data.filter(item => {
   const [startTime] = item.appointedSlot.split('-'); 
   const [hour, minute] = startTime.split(':').map(Number);
   
   const slotStartDate = new Date(item.day);
   slotStartDate.setHours(hour, minute, 0, 0);
 
   const slotStartTimestamp = slotStartDate.getTime();
 
   const diffMs = nowTimestamp - slotStartTimestamp;
 
   console.log('当前时间戳：', nowTimestamp, '时段开始时间戳：', slotStartTimestamp, '差值(ms)：', diffMs);
 
   return diffMs > (50 + 30) * 60 * 1000; // 咨询已结束且超过30分钟
 });
  
  console.log(recordsToProcess)
  
  const results = [];

  for (const record of recordsToProcess) {
    try {
      const { consultant, uid: userId, appointedSlot, day, _id } = record;

	  const {token:consultantToken} = await uniIDIns.createToken({uid:consultant});

		
      // 1. 调用 generateAndUploadChatLog
      const res = await uniCloud.callFunction({
        name: 'generateAndUploadChatLog',
        data: {
          uniIdToken: consultantToken,
          appointUserId: userId
        }
      });
		console.log(res);
      if (res.result.code !== 0 ) {
        results.push({ record, msg: 'generateAndUploadChatLog 失败', success: false });
        continue;
      }

      results.push({ record, msg: '成功生成记录', success: true });

    } catch (err) {
      console.error('处理失败:', err);
      results.push({ msg: err.message, success: false });
    }
  }
	console.log({
		code: 0,
		processed: results.length,
		results
	})
  return {
    code: 0,
    processed: results.length,
    results
  };
};
